<template>
  <a-spin :spinning="uploadLoading">
    <div class="translation-container">
      <div class="input-section">
        <div>
          <a-select v-model:value="source" style="width: 150px">
            <a-select-option value="auto">自动检测</a-select-option>
            <a-select-option v-for="item in conversions" :value="item.key">
              {{ item.value }}
            </a-select-option>
          </a-select>
          <span style="margin: 0 20px"> -> </span>
          <a-select v-model:value="target" style="width: 150px">
            <a-select-option v-for="item in conversions" :value="item.key">
              {{ item.value }}
            </a-select-option>
          </a-select>
        </div>
        <div style="margin-top: 20px">
          <a-textarea
            :disabled="loading"
            v-model:value="input"
            placeholder="请输入需要转换的内容"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            :bordered="false"
            @keydown.enter="pressEnter"
            autofocus
            class="input-textarea"
          />

          <!-- 工具栏 -->
          <div class="toolbar">
            <!-- 上传文件 -->
            <a-upload :custom-request="customRequest" :show-upload-list="false" :max-count="1">
              <a-tooltip title="上传文档">
                <span class="tool-btn">
                  <LinkOutlined />
                </span>
              </a-tooltip>
            </a-upload>

            <!-- 清空输入 -->
            <a-tooltip title="清空输入">
              <span class="tool-btn" @click="clearInput">
                <DeleteOutlined />
              </span>
            </a-tooltip>

            <!-- 提交按钮 -->
            <a-button
              type="primary"
              size="small"
              @click="submit"
              :loading="loading"
              class="submit-btn"
            >
              {{ loading ? '转换中...' : '发送' }}
            </a-button>
          </div>
        </div>
      </div>
      <!-- 右侧输出区 -->
      <div class="output-section">
        <div class="output-wrapper">
          <MarkdownRenderer v-if="output" :source="output" />
          <div v-else class="placeholder">转换结果将显示在这里...</div>
        </div>

        <!-- 控制按钮 -->
        <div class="output-footer">
          <a-tooltip title="复制转换结果">
            <a-button size="small" @click="copyOutput" class="action-btn">
              <CopyOutlined />
            </a-button>
          </a-tooltip>
          <a-tooltip title="停止转换">
            <a-button size="small" danger @click="stop" :disabled="!loading" class="action-btn">
              <StopOutlined />
            </a-button>
          </a-tooltip>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import Http from '@/api/http'
import { isLogin } from '@/stores/user'
import MarkdownRenderer from '@/views/component/MarkdownRenderer.vue'
import { CopyOutlined, DeleteOutlined, LinkOutlined, StopOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { onMounted, onUnmounted, ref } from 'vue'

const conversions = [
  { key: 'Properties', value: 'Properties' },
  { key: 'Yaml', value: 'Yaml' },
  { key: 'Xml', value: 'Xml' },
  { key: 'Sql', value: 'Sql' },
  { key: 'Json', value: 'Json' },
  { key: 'Java实体类', value: 'Java实体类' }
]
const input = ref('')
const output = ref('')
const loading = ref(false)
const uploadLoading = ref(false)
const stopFlag = ref(false)
const source = ref('auto')
const target = ref('Json')
const clientId = ref(null)

// SSE 实例
let eventSource = null

// 清空输入
const clearInput = () => {
  input.value = ''
}

// 复制输出
const copyOutput = async () => {
  if (!output.value) {
    message.warning('没有可复制的内容')
    return
  }
  try {
    await navigator.clipboard.writeText(output.value)
    message.success('已复制到剪贴板')
  } catch (err) {
    message.error('复制失败')
  }
}

// 回车处理
const pressEnter = (e) => {
  if (e.keyCode === 13) {
    if (e.shiftKey) {
      // Shift + Enter：换行
      return
    } else {
      // Enter：提交
      e.preventDefault()
      submit()
    }
  }
}

// 提交请求
const submit = () => {
  if (loading.value) {
    message.warning('请等待当前转换完成')
    return
  }
  if (!input.value.trim()) return

  output.value = ''
  loading.value = true
  stopFlag.value = false
  const requestParams = {
    chatId: generateId(),
    clientId: clientId.value,
    content: input.value,
    source: source.value,
    target: target.value
  }

  Http.post('/api/agent/conversion', requestParams)
}

const customRequest = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file)
  uploadLoading.value = true
  Http.post('/api/file/readFile', formData)
    .then((res) => {
      input.value = res
    })
    .catch((err) => {
      message.error('文件解析失败')
    })
    .finally((res) => {
      uploadLoading.value = false
    })
}

// 停止 SSE 流
const stop = () => {
  stopFlag.value = true
  loading.value = false
  message.info('已停止接收转换结果')
}

function generateId() {
  const timestamp = Date.now() // 毫秒级时间戳
  const randomNum = Math.floor(Math.random() * 10000) // 0-9999 的随机数
  return `${timestamp}${randomNum}`
}

// ========== 生命周期 ==========
onMounted(() => {
  if (!isLogin()) return
  clientId.value = generateId()
  const sseUrl = Http.baseUrl + '/sse/event/connect?clientId=' + clientId.value
  eventSource = new EventSource(sseUrl)
  eventSource.onmessage = (event) => {
    if (event.data === 'event: stop' || stopFlag.value === true) {
      loading.value = false
      return
    }

    try {
      const data = JSON.parse(event.data)
      if (data.content) {
        output.value += data.content
      }
    } catch (err) {}
  }

  eventSource.addEventListener('complete', () => {
    loading.value = false
  })

  eventSource.onerror = (err) => {
    loading.value = false
  }
})

onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
  }
})
</script>

<style scoped>
.translation-container {
  display: flex;
  height: 100vh;
  gap: 20px;
  padding: 20px;
  background: #f9faff;
  border-radius: 12px;
  font-family: 'Segoe UI', sans-serif;
}

.input-section,
.output-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.input-textarea {
  flex: 1;
  margin-bottom: 12px;
  font-size: 15px;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
}

.tool-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 8px;
  color: #595959;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-btn:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.submit-btn {
  margin-left: auto;
  height: 36px;
}

.output-section {
  border-left: 1px solid #e8e8e8;
  padding-left: 20px;
}

.output-wrapper {
  flex: 1;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  overflow-y: auto;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  font-size: 15px;
  line-height: 1.7;
}

.placeholder {
  color: #999;
  font-style: italic;
}

.output-footer {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.action-btn {
  width: 36px;
}
</style>
